package com.zcsy.manage.web.property;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.constants.OwnerConstants;
import com.zcsy.commons.model.RequestConstants;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.commons.unique.UniqueNumberUtils;
import com.zcsy.manage.model.base.CellHouse;
import com.zcsy.manage.model.base.CellInfo;
import com.zcsy.manage.model.pay.weixin.PayOrderResultRequest;
import com.zcsy.manage.model.pay.weixin.PayOrderResultResponse;
import com.zcsy.manage.model.property.FeeBill;
import com.zcsy.manage.model.property.FeeBillDetail;
import com.zcsy.manage.model.property.PayBillVo;
import com.zcsy.manage.model.system.Menu;
import com.zcsy.manage.model.system.User;
import com.zcsy.manage.service.base.ICellHouseService;
import com.zcsy.manage.service.base.ICellInfoService;
import com.zcsy.manage.service.property.IFeeBillDetailService;
import com.zcsy.manage.service.property.IFeeBillService;
import com.zcsy.manage.service.system.IMenuService;
import com.zcsy.manage.service.system.IUserService;
import com.zcsy.manage.web.tools.WXPayUtils;
/**
 * @author luoyz
 * @Description: 物业账单
 */
@Controller
@RequestMapping(value = "propertyBill")
public class PropertyBillController {

	@Autowired
	private IFeeBillDetailService feeBillDetailService;

	@Autowired
	private ICellHouseService cellHouseService;

	@Autowired
	private IFeeBillService feeBillService;
	
	@Autowired
	private IUserService userService;
	
	@Autowired
    private IMenuService menuService;

    @Autowired
    private ICellInfoService cellInfoService;

	/**
	 * @Description 我的账单
	 * @return
	 */
	@RequestMapping(value = "getMyBill", method = RequestMethod.GET)
	public String getMyBill(Model model, Integer payBill, HttpServletRequest req,
			HttpServletResponse resp) {

		User user = (User) req.getSession().getAttribute(
				RequestConstants.USER_SESSION_ID);
		String userID = user.getId();

		// 获取业主房屋信息
		List<CellHouse> houses = cellHouseService.getListByOwnerIdAndState(userID, OwnerConstants.NORMAL_HOUSE_STATE);

		// 获取房屋id的集合
		List<String> housesID = new ArrayList<String>();
		Iterator<CellHouse> iterator = houses.iterator();
		while (iterator.hasNext()) {
			CellHouse house = (CellHouse) iterator.next();
			housesID.add(house.getId());
		}
		// 根据房屋id查询欠费账单
		List<FeeBillDetail> feeBillDetail = feeBillDetailService
				.selectFeeBillDetailByHouseId(housesID);

		// 写入房屋的名称
		Iterator<FeeBillDetail> iteratorfeeBill = feeBillDetail.iterator();
		while (iteratorfeeBill.hasNext()) {
			FeeBillDetail detail = (FeeBillDetail) iteratorfeeBill.next();
			if (detail.getName() != null) {
				detail.setHouseFullName(detail.getCellName()
						+ detail.getRegionName() + detail.getBuildingName()
						+ detail.getUnitName() + detail.getName());

			}
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy.MM.dd");
			SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy");
			SimpleDateFormat monthFormat = new SimpleDateFormat("M");
			if (detail.getStartDate() != null) {
				String startDateString = formatter
						.format(detail.getStartDate());
				detail.setStartDateString(startDateString);
				String startDateYear = yearFormat.format(detail.getStartDate());
				detail.setStartDateYear(startDateYear);
				String startDateMonth = monthFormat.format(detail
						.getStartDate());
				detail.setStartDateMonth(startDateMonth);
			}
			if (detail.getEndDate() != null) {
				String endDateString = formatter.format(detail.getEndDate());
				detail.setEndDateString(endDateString);
			}

		}
		
        checkingPropertyRightByCellId(req, model);
        checkingCarRightByCellId(req, model);

        model.addAttribute("feeBillDetail", feeBillDetail);
        model.addAttribute("ownerName", user.getUsername());
        model.addAttribute("payBill", payBill);
        return "property/feebill/myBill";
	}

	/**
	 * @Description 物业费-我要缴费-缴费信息
	 * @return
	 */
	@RequestMapping(value = "getPayBillInfo", method = RequestMethod.GET)
	public String getPayBillInfo(Model model,String houseId, final HttpServletRequest req,
			HttpServletResponse response) throws Exception {
		User user = (User) req.getSession().getAttribute(
				RequestConstants.USER_SESSION_ID);
		String userID = user.getId();
		// 获取业主房屋信息
		List<CellHouse> houses = cellHouseService.getListByOwnerIdAndState(
				userID, OwnerConstants.NORMAL_HOUSE_STATE);
		for (CellHouse cellHouse : houses) {
			cellHouse.setFullName(cellHouse.getCellName()
					+ cellHouse.getRegionName() + cellHouse.getBuildingName()
					+ cellHouse.getUnitName() + cellHouse.getName());
		}

		model.addAttribute("houses", houses);
		model.addAttribute("houseId", houseId);
		return "property/feebill/payBill";

	}

	/**
	 * @Description: 物业费-我要缴费，通过月数和房屋id获取相关信息返回页面
	 * @param houseId 房屋id
	 * @param months 缴费月数
	 * @author huangls 1449700087@qq.com
	 * @date 2016年8月17日
	 */
	@RequestMapping(value = "getHousePropertyInfo", method = RequestMethod.GET)
	@ResponseBody
	public RequestJson getHousePropertyInfo( String houseId, Integer months) {

		RequestJson result = new RequestJson();

		try {
			CellHouse cellHouse = cellHouseService.getHousePropertyInfo(houseId);

			// 根据房屋id查询最后一条成功的详细记录
			FeeBillDetail lastFeeBillDetail = feeBillDetailService.selectLastBill(houseId);
			
			PayBillVo  payBillVo = new PayBillVo();
			if (cellHouse != null) {
			
				Date startDate = new Date();
				Date endDate = new Date();
				
				if(lastFeeBillDetail != null){
					Date lastEndDate = lastFeeBillDetail.getEndDate();
					// 最后一条记录的结束时间加一天作为新的起始时间
					Calendar cal = Calendar.getInstance();
					cal.setTime(lastEndDate);
					cal.add(Calendar.DATE, 1);
					startDate = cal.getTime();
				}
				
				//进行日期加月份的计算，获得账单结束时间
				Calendar date = Calendar.getInstance();
				if(startDate != null){
					date.setTime(startDate);
					date.add(Calendar.MONTH, months);
				} else {
					date.add(Calendar.MONTH, months);
				}
				endDate=date.getTime();
				
				//将时间转化为固定格式的字符串
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				String eDate = sdf.format(endDate);
				String sDate = sdf.format(startDate);
				
				//将所需信息封装在payBillVo对象中
				payBillVo.setArea(cellHouse.getArea());
				payBillVo.setPerPrice(cellHouse.getPerPrice());
				payBillVo.setStartDate(sDate);
				payBillVo.setEndDate(eDate);
			
				result.setSuccess(true);
				result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
				result.setMsg("数据获取成功！");
				result.setObj(payBillVo);
			} else {
				result.setSuccess(false);
				result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
				result.setMsg("物业费账单未初始化！");
			}
		} catch (Exception e) {
			result.setSuccess(false);
			result.setResultCode(OwnerConstants.GET_USERINFO_FALSE);
			result.setMsg("网络异常");
		}

		return result;
	}
	
	/**
	 * @Description:我要缴费提交，生成账单和账单详情
	 * @param houseId 房屋id
	 * @param months 缴费月数
	 * @return 返回我的账单页面
	 * @author huangls 1449700087@qq.com
	 * @date 2016年8月17日
	 */
	@RequestMapping(value = "saveManagementBill", method = RequestMethod.POST)
	@ResponseBody
	public RequestJson saveManagementBill( String houseId, Integer months, String billTitle, HttpServletRequest req) {

		RequestJson result = new RequestJson();

		try {
			
//			CellHouse cellHouse = cellHouseService.getHousePropertyInfo(houseId);
			User user = (User) req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
//			FeeBill feeBill = new FeeBill();
//			FeeBillDetail feeBillDetail = new FeeBillDetail();

			// 根据房屋id查询最后一条成功的详细记录
			FeeBillDetail lastFeeBillDetail = feeBillDetailService.selectLastBill(houseId);
			if ( houseId != null && null != lastFeeBillDetail) {
				// 生成物业费账单
			    FeeBillDetail feeBillDetail = feeBillDetailService.submitFeeOrder(houseId, months, billTitle, user);

//				Date startDate = new Date();
//				Date endDate = new Date();
//				
//				if(lastFeeBillDetail != null){
//					Date lastEndDate = lastFeeBillDetail.getEndDate();
//					// 最后一条记录的结束时间加一天作为新的起始时间
//					Calendar cal = Calendar.getInstance();
//					cal.setTime(lastEndDate);
//					cal.add(Calendar.DATE, 1);
//					startDate = cal.getTime();
//				}
//				
//				//进行日期加月份的计算，获得账单结束时间
//				Calendar date = Calendar.getInstance();
//				if(startDate != null){
//					date.setTime(startDate);
//					date.add(Calendar.MONTH, months);
//				} else {
//					date.add(Calendar.MONTH, months);
//				}
//				endDate=date.getTime();
//				
//				//生成账单
//				feeBill.setId(UniqueNumberUtils.get18UniqueNumber());
//				feeBill.setCellId(cellHouse.getCellId());
//				feeBill.setHouseId(houseId);
//				Date now = new Date();
//				feeBill.setSendTime(now);
//				feeBillService.insert(feeBill);
//				
//				//生成账单详情
//				feeBillDetail.setId(UniqueNumberUtils.get18UniqueNumber());
//				feeBillDetail.setBillId(feeBill.getId());
//				feeBillDetail.setStartDate(startDate);
//				feeBillDetail.setEndDate(endDate);
//				feeBillDetail.setMonth(months);
//				feeBillDetail.setArea(cellHouse.getArea());
//				feeBillDetail.setUnitPrice(cellHouse.getPerPrice());
//				feeBillDetail.setRate(Constants.INIT_RATE);
//				
//				BigDecimal area = cellHouse.getArea();
//				BigDecimal perPrice = cellHouse.getPerPrice();
//				BigDecimal temp = new BigDecimal(months);
//				BigDecimal money = area.multiply(perPrice).multiply(temp).multiply(Constants.INIT_RATE);
//				
//				feeBillDetail.setMoney(money);
//				feeBillDetail.setState(Constants.BEFORE_STATE);
//				feeBillDetail.setGenerateWay(Constants.BEFORE_STATE);
//				feeBillDetail.setOperatorType(Constants.OWNER_TYPE);
//				feeBillDetail.setOperator(user.getUsername());
//				feeBillDetail.setOperatorAccount(user.getLoginname());
//				feeBillDetail.setCreateTime(now);
//				feeBillDetail.setBillTitle(billTitle);
//				feeBillDetailService.insert(feeBillDetail);
				
			    result.setObj(feeBillDetail.getId());
				result.setSuccess(true);
				result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
				result.setMsg("数据获取成功！");
				
			}  else {
				result.setSuccess(false);
				result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
				result.setMsg("物业费账单未初始化！");
			}
		} catch (Exception e) {
			result.setSuccess(false);
			result.setResultCode(OwnerConstants.GET_USERINFO_FALSE);
			result.setMsg("网络异常");
		}

		return result;
	}

	/**
	 * @Description 物业缴费-缴费记录列表
	 * @param model
	 * @param req
	 * @param resp
	 * @param pageNo
	 * @param pageSize
	 * @return
	 * @throws RuntimeException
	 */
	@RequestMapping(value = "propertyFeePaymentList", method = RequestMethod.GET)
	public String propertyFeePaymentList(Model model,
			final HttpServletRequest req) throws RuntimeException {

		// 缴费信息
		List<FeeBillDetail> feeBillList = null;

		User user = (User) req.getSession().getAttribute(
				RequestConstants.USER_SESSION_ID);
		String userID = user.getId();

		// 获取业主房屋信息
		List<CellHouse> houses = cellHouseService.getListByOwnerIdAndState(
				userID, OwnerConstants.NORMAL_HOUSE_STATE);

		// 获取房屋id的集合
		List<String> housesID = new ArrayList<String>();
		Iterator<CellHouse> iterator = houses.iterator();
		while (iterator.hasNext()) {
			CellHouse house = (CellHouse) iterator.next();
			housesID.add(house.getId());
		}
		// 根据房屋id查询账单列表
		feeBillList = feeBillService.getWyBillRecord(housesID);
		// 写入房屋的名称
		Iterator<FeeBillDetail> iteratorfeeBillList = feeBillList.iterator();
		while (iteratorfeeBillList.hasNext()) {
			FeeBillDetail detail = (FeeBillDetail) iteratorfeeBillList.next();
			detail.setHouseFullName(detail.getCellName()
					+ detail.getRegionName() + detail.getBuildingName()
					+ detail.getUnitName() + detail.getName());
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy.MM.dd");
			if (detail.getStartDate() != null) {
				String payTime = formatter.format(detail.getPayTime());
				detail.setPayTimeString(payTime);
			}
		}
		model.addAttribute("feeBillList", feeBillList);
		return "property/feebill/billRecord";
	}

	/**
	 * @Method: propertyFeePaymentDetail
	 * @Description 物业缴费-缴费记录详单
	 * @param token
	 *            billID 账单id
	 * @return paymentTime String 缴费时间 totalAmount double 合计金额 ownerHouse String
	 *         房屋 period String 缴费时间段 houseArea double 房屋面积 price double 物业费单价
	 *         baseNumber int 物业费基数 paymentStatus bool 缴费状态 paymentType int 缴费方式
	 *         operator String 操作人
	 * @throws RuntimeException
	 * @see
	 */
	@RequestMapping(value = "propertyFeePaymentDetail", method = RequestMethod.GET)
	public String propertyFeePaymentDetail(Model model, String billID)
			throws RuntimeException {

		// 根据房屋id查询账单详情
		FeeBillDetail feeBillDetail = feeBillDetailService.selectByPrimaryKey(billID);
		FeeBill feeBill = feeBillService.selectByPrimaryKey(feeBillDetail.getBillId());
		String houseID = feeBill.getHouseId();
		CellHouse cellHouse = cellHouseService.selectByPrimaryKey(houseID);
		// 写入房屋的名称
		if (cellHouse.getName()!=null) {
			feeBillDetail.setHouseFullName(cellHouse.getCellName()
					+ cellHouse.getRegionName() + cellHouse.getBuildingName()
					+ cellHouse.getUnitName() + cellHouse.getName());
		}
		Integer state = feeBillDetail.getState();
		if (state == 0) {
			feeBillDetail.setPayStateString("缴费成功");
			Integer payWay = feeBillDetail.getPayWay();
			if (payWay == 0) {
				feeBillDetail.setPayWayString("后台缴费 ");
			} else if (payWay == 1) {
				feeBillDetail.setPayWayString("支付宝");
			} else if (payWay == 2) {
				feeBillDetail.setPayWayString("翼支付 ");
			} else {
				feeBillDetail.setPayWayString("微信 ");
			}
			SimpleDateFormat formatterPay = new SimpleDateFormat(
					"yyyy.MM.dd hh:mm:ss");
			if (feeBillDetail.getPayTime() != null) {
				String payTimeString = formatterPay.format(feeBillDetail
						.getPayTime());
				feeBillDetail.setPayTimeString(payTimeString);
			}
		} else if (state == 1) {
			feeBillDetail.setPayStateString("欠费");
			feeBillDetail.setPayWayString("");
			feeBillDetail.setPayTimeString("");
		} else if (state == 3) {
			feeBillDetail.setPayStateString("预缴费");
			feeBillDetail.setPayWayString("");
			feeBillDetail.setPayTimeString("");
		} else {
			feeBillDetail.setPayStateString("已删除");
			feeBillDetail.setPayWayString("");
			feeBillDetail.setPayTimeString("");
		}

		SimpleDateFormat formatter = new SimpleDateFormat("yyyy.MM.dd");
		if (feeBillDetail.getStartDate() != null) {
			String startDateString = formatter.format(feeBillDetail
					.getStartDate());
			feeBillDetail.setStartDateString(startDateString);
		}
		if (feeBillDetail.getEndDate() != null) {
			String endDateString = formatter.format(feeBillDetail.getEndDate());
			feeBillDetail.setEndDateString(endDateString);
		}
		model.addAttribute("billID", billID);
		model.addAttribute("feeBillDetail", feeBillDetail);
		// model.addAttribute("houseFullName",houseFullName);
		return "property/feebill/propertyBillDetail";

	}

	/**
	 * @Method: submitPaymentRange
	 * @Description 缴物业费提交（计算缴费起始时间）
	 * @param houseId 房屋ID
	 * @return startDate 起始时间
	 * @see
	 */
	@RequestMapping(value = "submitPaymentRange", method = RequestMethod.GET)
	@ResponseBody
	public RequestJson submitPaymentRange(String houseId) {

		RequestJson result = new RequestJson();
		// 根据房屋id查询最后一条成功的详细记录
		FeeBillDetail lastFeeBillDetail = feeBillDetailService.selectLastBill(houseId);
		if (lastFeeBillDetail != null) {
			Date lastEndDate = lastFeeBillDetail.getEndDate();
			// 最后一条记录的结束时间加一天作为新的起始时间
			Calendar cal = Calendar.getInstance();
			cal.setTime(lastEndDate);
			cal.add(Calendar.DATE, 1);
			Date startDate = cal.getTime();

			result.setObj(startDate);
			result.setSuccess(true);
			result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
			result.setMsg("查询起始时间成功");

		} else {
			result.setSuccess(false);
			result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
			result.setMsg("未查询到历史账单信息");
		}

		return result;
	}

	@RequestMapping(value = "getHouseWithProperty", method = RequestMethod.GET)
	@ResponseBody
	public RequestJson getHouseWithProperty(String houseId) {

		RequestJson result = new RequestJson();

		try {
			FeeBillDetail feeBillDetail = feeBillDetailService
					.selectLastBill(houseId);
			if (feeBillDetail != null) {
				feeBillDetail.setPayStateString(Constants.getPayState(feeBillDetail.getState()));
				SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日");
				if (feeBillDetail.getEndDate() != null) {
					String endDateString = formatter.format(feeBillDetail
							.getEndDate());
					feeBillDetail.setEndDateString(endDateString);
				}

				result.setSuccess(true);
				result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
				result.setMsg("数据获取成功！");
				result.setObj(feeBillDetail);
			} else {
				result.setSuccess(false);
				result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
				result.setMsg("物业费账单未初始化");
			}
		} catch (Exception e) {
			result.setSuccess(false);
			result.setResultCode(OwnerConstants.GET_USERINFO_FALSE);
			result.setMsg("网络异常");
		}

		return result;
	}

	@RequestMapping(value = "payFeeBill", method = RequestMethod.GET)
    public String payFeeBill(Model model, String billId, HttpServletRequest request) {

        // 根据房屋id查询账单详情
        FeeBillDetail feeBillDetail = feeBillDetailService.selectByPrimaryKey(billId);
        
        // 更新当前操作人
        User user = (User) request.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        feeBillDetail.setOperator(user.getId());
        feeBillDetail.setOperatorAccount(user.getLoginname());
        
        feeBillDetailService.updateByPrimaryKey(feeBillDetail);
        
        model.addAttribute("feeBillDetail", feeBillDetail);
        return "property/feebill/pay_bill";
    }
	
	@RequestMapping(value="wxPayResult" , method = RequestMethod.GET)
    @ResponseBody
    public RequestJson wxPayResult(String orderNumber, HttpServletRequest request,
            HttpServletResponse response) {
        RequestJson result = new RequestJson();
        try {
            PayOrderResultRequest resultReq = new PayOrderResultRequest();
            resultReq.setOut_trade_no(orderNumber);
            String requestXml = WXPayUtils.createWXPayResultRequest(resultReq);
            PayOrderResultResponse payResult = WXPayUtils.getPayResult(requestXml);
            
            // 根据微信文档return_code 和result_code都为SUCCESS的时候才会返回code_url
            if(null != payResult) {
                if("SUCCESS".equals(payResult.getReturn_code()) && "SUCCESS".equals(payResult.getResult_code())){
                    if("SUCCESS".equals(payResult.getTrade_state())){
                        feeBillDetailService.payFeeBill(orderNumber, payResult);
                    } else {
                        result.setMsg(payResult.getTrade_state_desc());
                        result.setSuccess(false);
                    }
                } else {
                    result.setMsg(payResult.getErr_code_des()); 
                    result.setSuccess(false);
                }
            } else {
                result.setMsg("请求支付结果失败"); 
                result.setSuccess(false);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg(RequestConstants.NET_ERROR);
            result.setSuccess(false);
        }
        return result;
    }
	

    /**
     * @description 检验此小区是否具有缴纳停车费的权限
     * @param cellId 小区id
     * @author chenxin
     * @date 2016年8月31日下午6:54:39
     */
    public void checkingCarRightByCellId(HttpServletRequest request, Model model) {
        User user = (User)request.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        CellInfo cellInfo = user.getCurrentCell();
        String cellId = cellInfo.getId();
        
        List<String> list = cellInfoService.getMenusByCellId(cellId, Constants.SYSTEM_OWNER);
        
        for (String item : list) {
            Menu menu = menuService.getMenuById(item);
            String value = menu.getValue();
            if(StringUtils.equals(value, "owner.car")) {
                model.addAttribute("displayCar", Constants.STATE_ENABLED);
            }  
        }
    }
    
    /**
     * @description 检验此小区是否具有缴纳物业费的权限     
     * @param cellId 小区id                 
     * @author chenxin
     * @date 2016年8月31日下午6:54:39
     */
    public void checkingPropertyRightByCellId(HttpServletRequest request, Model model) {
        User user = (User)request.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        CellInfo cellInfo = user.getCurrentCell();
        String cellId = cellInfo.getId(); 
        
        List<String> list = cellInfoService.getMenusByCellId(cellId, Constants.SYSTEM_OWNER);
        
        for (String item : list) {
            Menu menu = menuService.getMenuById(item);
            String value = menu.getValue();
            if (StringUtils.equals(value, "owner.propertyFee")) {
                model.addAttribute("displayFeeBill", Constants.STATE_ENABLED);
            }
        }
    }

}
